package proffesorintro;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.andro.chansung.ConstantName;
import com.andro.chansung.ConstantURL;
import com.andro.chansung.DB;

import departmentintro.Proffesor;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

public class DeparmentProffesorUpdateThread extends Thread {
	
	private Activity activity;
	private Handler handler;
	
	public DeparmentProffesorUpdateThread(Activity activity, Handler handler) {
		this.activity = activity;
		this.handler = handler;
	}
	
	public void run() {
		try {
			Document doc = Jsoup.connect(ConstantURL.DEPARTMENT_PROFFESOR_INTRO_URL).get();
			Elements proffesors = doc.select("proffesor");
			
			SQLiteDatabase db = activity.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
			//
			for( Element element : proffesors ) {
				Proffesor proffesor = new Proffesor(element.getElementsByTag("name").get(0).text(),
													element.getElementsByTag("degree").get(0).text(), 
													element.getElementsByTag("major").get(0).text(), 
													element.getElementsByTag("lab").get(0).text(), 
													element.getElementsByTag("email").get(0).text(), 
													element.getElementsByTag("img_src").get(0).text());
				DB.insertDataIntoProffesorTable(db, proffesor);
			}			
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);
	}

}
